package org.zuel.huhuForum.controller.interceptor;


import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.zuel.huhuForum.model.User;
import org.zuel.huhuForum.param.LoginTicket;
import org.zuel.huhuForum.service.IUserService;
import org.zuel.huhuForum.service.Impl.UserService;
import org.zuel.huhuForum.util.CookieUtil;
import org.zuel.huhuForum.util.HostHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.util.Date;

@Component
@Log4j2
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService userService;

    @Autowired
    private HostHolder hostHolder;

    /**
     * 在 Controller 执行之前被调用
     * 检查凭证状态，若凭证有效则在本次请求中持有该用户信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 cookie 中获取凭证
        String ticket = request.getHeader("ticket");
        if (ticket != null) {
            // 查询凭证
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            // 检查凭证状态（是否有效）以及是否过期
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                // 根据凭证查询用户
                User user = userService.findUserById(loginTicket.getUserId());
                // 在本次请求中持有用户信息
                hostHolder.setUser(user);
                log.info("用户"+user.getEmail()+"请求服务中...");
//                 构建用户认证的结果，并存入 SecurityContext, 以便于 Spring Security 进行授权
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), userService.getAuthorities(user.getId()));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }else{

            log.info("未识别出ticket...");
            log.info("addr:  "+request.getRemoteAddr());
        }
        return true;
    }

}
